package com.smile.cloud.admin.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.smile.cloud.admin.bo.UserDetail;
import com.smile.cloud.admin.dto.UserLoginForm;
import com.smile.cloud.admin.dto.UserRegisterForm;
import com.smile.cloud.admin.service.AuthService;
import com.smile.cloud.admin.vo.UserDetailVo;
import com.smile.cloud.common.base.api.ApiController;
import com.smile.cloud.common.base.result.CommonResult;
import com.smile.cloud.mbg.base.model.SysUser;
import com.sun.xml.internal.ws.api.message.Attachment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author smile
 * @ClassName AdminController
 * @Description TODO
 * @Date 2020/4/11
 * @Version V1.0
 **/
@Slf4j
@ApiController
@Api(tags = "SysUserController 用户")
@RequestMapping("/v1/api/user")
public class SysUserController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AuthService authService;

    @ApiOperation(value = "用户注册")
    @PostMapping(value = "/register")
    public CommonResult<SysUser> register(@Valid @RequestBody UserRegisterForm userRegisterForm) throws Exception {
        SysUser sysUser = authService.register(userRegisterForm);
        if (sysUser == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(sysUser);
    }

    @ApiOperation(value = "用户登录")
    @PostMapping(value = "/login")
    public Object login(@Valid @RequestBody UserLoginForm userLoginForm) {
        String uuidAccount = userLoginForm.getSaasCode() + "_" + userLoginForm.getUsername();
        String token = authService.login(uuidAccount, userLoginForm.getPassword());
        Map<String, String> tokenMap = new HashMap<>();
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return tokenMap;
    }

    @ApiOperation(value = "根据token获取用户信息")
    @PostMapping(value = "/getUserDetailByToken")
    public UserDetailVo getUserDetailByToken(HttpServletRequest request) throws Exception {
        UserDetailVo userDetailVo = new UserDetailVo();
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());
            userDetailVo = authService.getUserDetailByToken(authToken);
        }
        return userDetailVo;
    }


    @ApiOperation(value = "detail")
    @PostMapping(value = "/detail")
    public CommonResult<UserDetail> userDetail(@Valid @RequestBody UserLoginForm userLoginForm) {
        String uuidAccount = userLoginForm.getSaasCode() + "_" + userLoginForm.getUsername();
        UserDetail userDetail = (UserDetail) authService.loadUserByUsername(uuidAccount);
        return CommonResult.success(userDetail);
    }


    public void delAttachment() {
        ThreadPoolExecutor executor = null;
        try {
            List<Attachment> attachments = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(attachments) && attachments.size() > 0) {
                executor = new ThreadPoolExecutor(
                        10,
                        100,
                        3,
                        TimeUnit.SECONDS,
                        new LinkedBlockingQueue<>(),
                        new ThreadFactoryBuilder().setNameFormat("XX-del-attachment-task-%d").build());

                CompletableFuture.supplyAsync(() -> {
                    log.info("远程删除附件。。。");
                    return 100;
                }).thenApply(result -> {
                    log.info("删除数据库附件");
                    return result;
                }).exceptionally(e -> {
                    log.info("数据库回滚操作");
                    log.error(e.getMessage());
                    return 0;
                });
            }
        } catch (Exception e) {
            log.error("删除异常{0}", e);
        } finally {
            if (executor != null) {
                executor.shutdown();
            }
        }

    }
}
